<script setup>
import Fruit from './components/fruit.vue'
import {ref} from 'vue'

const myInput = ref()

const list = ref([])

const inputVal = ref('')

const addItem = () => {
  // 处理数据已经存在的情况, 用 数组 some 方法可以判断是否有满足条件的数据
  const isExist = list.value.some(item=>item.name === inputVal.value)
  if(isExist) return

  list.value.push({
    id: Date.now(),
    name: inputVal.value
  })

  inputVal.value = ''
  myInput.value.focus()
}

const delItem = (id) => {
  list.value = list.value.filter(item=>item.id !== id)
}
</script>

<template>
  <div class="inputBar">
    <input type="text" v-model="inputVal" ref="myInput">
    <button @click="addItem">添加</button>
  </div>

  <div class="list">
    <Fruit v-for="item in list" :key="item.id" :item="item" @delItem="delItem"/>
  </div>
</template>